//实现文件存储 子服务
//实现文件rpc服务类 --实现rpc调用接口
//实现文件存储服务类 --实现文件存储接口
//实现文件存储构造者

#include <brpc/server.h>
#include <butil/logging.h>
//实现语音识别子服务
#include "etcd.hpp"     //服务注册
#include "logger.hpp"   //日志模块
#include "base.pb.h"  //protobuf框架代码
#include "file.pb.h"  //protobuf框架代码
#include "utils.hpp"
namespace xchat
{
class FileServiceImpl : public xchat::FileService
{
    public:
    FileServiceImpl(const std::string& storage_path)
        : _storage_path(storage_path)
    {
        umask(0);
        mkdir(storage_path.c_str(), 0775);
        if(_storage_path.back() != '/')
        {
            _storage_path += '/';
        }
    }
    ~FileServiceImpl(){}
    void GetSingleFile(google::protobuf::RpcController* controller,
                    const ::xchat::GetSingleFileReq* request,
                    ::xchat::GetSingleFileRsp* response,
                    ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done);
        response->set_request_id(request->request_id());
        //取出请求的文件id 
        std::string fid = request->file_id();
        std::string file_name = _storage_path + fid;
        //用文件id 取出文件 id作为文件名
        std::string body;
        bool ret = xchat::readFile(file_name, body);
        if(ret == false)
        {
            response->set_success(false);
            response->set_errmsg("读取文件数据失败");
            LOG_ERROR("{} 读取文件数据失败!", request->request_id());
            return;
        }
        //组织响应
        response->set_success(true);
        response->mutable_file_data()->set_file_id(fid);
        response->mutable_file_data()->set_file_content(body);
    }
    void GetMultiFile(google::protobuf::RpcController* controller,
                    const ::xchat::GetMultiFileReq* request,
                    ::xchat::GetMultiFileRsp* response,
                    ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done);
        response->set_request_id(request->request_id());
        for(int i = 0; i < request->file_id_list_size(); i++)
        {
            //取出请求的文件id 
            std::string fid = request->file_id_list(i);
            std::string file_name = _storage_path + fid;
            //用文件id 取出文件 id作为文件名
            std::string body;
            bool ret = xchat::readFile(file_name, body);
            if(ret == false)
            {
                response->set_success(false);
                response->set_errmsg("读取文件数据失败");
                LOG_ERROR("{}读取文件数据失败!", request->request_id());
                return;
            }
            //组织响应
            FileDownloadData data;
            data.set_file_id(fid);
            data.set_file_content(body);
            response->mutable_file_data()->insert({fid, data});
            
        }
        response->set_success(true);
    }
    void PutSingleFile(google::protobuf::RpcController* controller,
                    const ::xchat::PutSingleFileReq* request,
                    ::xchat::PutSingleFileRsp* response,
                    ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done);
        response->set_request_id(request->request_id());
        //为文件生成一个唯一的uuid作为文件名
        std::string fid = uuid();
        std::string file_name = _storage_path + fid;
        //std::cout << file_name << std::endl;
        //取出文件数据 进行磁盘写入
        bool ret = xchat::writeFile(file_name, request->file_data().file_content());
        if(ret == false)
        {
            response->set_success(false);
            response->set_errmsg("写入文件数据失败");
            LOG_ERROR("{}写入文件数据失败!", request->request_id());
            return;
        }
        //组织相应
        response->mutable_file_info()->set_file_id(fid);
        response->mutable_file_info()->set_file_size(request->file_data().file_size());
        response->mutable_file_info()->set_file_name(request->file_data().file_name());

        response->set_success(true);
    }
    void PutMultiFile(google::protobuf::RpcController* controller,
                    const ::xchat::PutMultiFileReq* request,
                    ::xchat::PutMultiFileRsp* response,
                    ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpc_guard(done);
        response->set_request_id(request->request_id());
                for(int i = 0; i < request->file_data_size(); i++)
        {
            std::string fid = uuid();
            std::string file_name = _storage_path + fid;
            //取出文件数据 进行磁盘写入
            bool ret = xchat::writeFile(file_name, request->file_data(i).file_content());
            if(ret == false)
            {
                response->set_success(false);
                response->set_errmsg("写入文件数据失败");
                LOG_ERROR("{}写入文件数据失败!", request->request_id());
                return;
            }
            //组织相应
            xchat::FileMessageInfo *info = response->add_file_info();
            info->set_file_id(fid);
            info->set_file_size(request->file_data(i).file_size());
            info->set_file_name(request->file_data(i).file_name());
        }
        response->set_success(true);
    }
    private:
        std::string _storage_path;
};
class FileServer
{
    public:
        using ptr = std::shared_ptr<FileServer>;
        FileServer(const Registry::ptr &reg_client, const std::shared_ptr<brpc::Server> &server)
            :_reg_client(reg_client), _rpc_server(server)
        {}
        ~FileServer()
        {}

        //搭建rpc服务器 并启动服务器
        void start()
        {
            _rpc_server->RunUntilAskedToQuit();
        }
    private:
        Registry::ptr _reg_client;  //注册中心
        std::shared_ptr<brpc::Server> _rpc_server;       //rpc服务
};
class FileServerBuilder
{
    public:
        //用于构造服务注册客户端对象  服务中心地址 服务名称 当前实例的外部访问地址
        void make_reg_object(const std::string &reg_host, const std::string server_name, const std::string &access_host)
        {
            _reg_client = std::make_shared<Registry>(reg_host);
            _reg_client->registry(server_name, access_host);
        }
        void make_rpc_server(uint16_t port, uint32_t timeout, uint8_t num_threads, const std::string &storage_path = "./data/")
        {
            _rpc_server = std::make_shared<brpc::Server>();
            FileServiceImpl *File_service = new FileServiceImpl(storage_path); 
            int ret = _rpc_server->AddService(File_service, brpc::ServiceOwnership::SERVER_OWNS_SERVICE);
            if(ret == -1)
            {
                LOG_ERROR("添加rpc服务失败!");
                abort();
            }
            brpc::ServerOptions options;
            options.idle_timeout_sec = timeout;  //连接空闲超时时间-超时后连接被关闭
            options.num_threads = num_threads;        //io线程数量
            //4.启动服务器
            ret = _rpc_server->Start(port, &options);
            if(ret == -1)
            {
                LOG_ERROR("启动rpc服务器失败!");
                abort();
            }

        }
        FileServer::ptr build()
        {
            //_rpc_server 构造前 其余的得构造好
            if (!_reg_client)
            {
                LOG_ERROR("服务注册客户端对象未构造!");
                abort();
            }
            if(!_rpc_server)
            {
                LOG_ERROR("rpc服务对象未构造!");
                abort();
            }
            FileServer::ptr server = std::make_shared<FileServer>(_reg_client, _rpc_server);
            return server;
        }
    private:
        Registry::ptr _reg_client;  //注册中心
        std::shared_ptr<brpc::Server> _rpc_server;       //rpc服务
};

}